<template>
    <el-container>
        <el-aside>
            <el-menu default-active="1" class="el-menu-vertical-demo" mode="vertical">
                <el-menu-item index="1">挂号系统</el-menu-item>
            </el-menu>
        </el-aside>

        <el-main>
            <el-card :body-style="{ padding: '20px' }">
                <h3>挂号信息</h3>

                <!-- 患者信息展示 -->
                <el-form-menu class="e-form">
                    <el-form-item label="患者姓名">
                        <el-input v-model="patient.name" disabled />
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-input v-model="patient.gender" disabled />
                    </el-form-item>
                    <el-form-item label="年龄">
                        <el-input v-model="patient.age" disabled />
                    </el-form-item>
                    <el-form-item label="住址">
                        <el-input v-model="patient.address" disabled />
                    </el-form-item>
                    <el-form-item label="电话号码">
                        <el-input v-model="patient.contactPhone" disabled />
                    </el-form-item>
                    <el-form-item label="身份证号码">
                        <el-input v-model="patient.idNumber" disabled />
                    </el-form-item>
                </el-form-menu>


                <el-divider></el-divider>

                <!-- 科室选择 -->
                <el-form :model="form" label-width="120px">
                    <el-form-item label="选择部门">
                        <el-select v-model="form.type" placeholder="请选择部门">
                            <el-option label="门诊部" value="门诊部"></el-option>
                            <el-option label="住院部" value="住院部"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="选择科室" :rules="[{ required: true, message: '请选择科室', trigger: 'change' }]">
                        <el-select v-model="form.departmentId" placeholder="请选择科室">
                            <el-option v-for="department in columns" :label="department.name" :value="department.id"
                                :key="department.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 日期选择 -->
                    <el-form-item label="选择挂号日期" :rules="[{ required: true, message: '请选择挂号日期', trigger: 'change' }]">
                        <el-date-picker v-model="form.createTime" type="date" placeholder="请选择挂号日期" disabled />
                    </el-form-item>

                    <!-- 挂号状态 -->
                    <el-form-item label="挂号状态" :rules="[{ required: true, message: '请选择挂号状态', trigger: 'change' }]">
                        <el-select v-model="form.status" placeholder="请选择挂号状态" disabled>
                            <el-option label="已挂号" value="1"></el-option>
                            <el-option label="待挂号" value="0"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 提交按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="handlePostPayment">挂号缴费</el-button>
                        <el-button type="primary" @click="submitRegistration">提交挂号</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-main>
        <el-dialog v-model="dialogVisible" style="width: 1000px;height: 80vh;">
            <iframe src="" :srcdoc="payPageHtml" style="height: 70vh;"></iframe>
        </el-dialog>
    </el-container>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { usePatientStore } from '@/utils/stores/patient'
import { GetDepartments, PostDepartment } from '@/api/DepartmentService'
import { PostPayment } from '@/api/PaymentService'
import { PostRegistration } from '@/api/RegistrationService'
import { PostOrder } from '@/api/OrderService'

// 使用 store 获取患者信息
const patientStore = usePatientStore()
const patient = ref<any>({})

const generateUniqueId = () => {
    const now = new Date()
    const timestamp =
        now.getFullYear() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0') +
        String(now.getHours()).padStart(2, '0') +
        String(now.getMinutes()).padStart(2, '0') +
        String(now.getSeconds()).padStart(2, '0') +
        String(now.getMilliseconds()).padStart(3, '0')
    // 生成随机数部分（1000-9999）
    const randomPart = Math.floor(Math.random() * 9000) + 1000
    const uniqueId = timestamp + randomPart
    return uniqueId
}

// 初始化表单数据
const form = ref({
    id: 0,
    createTime: new Date(),
    order: "",
    patientId: '',
    departmentId: '',
    status: '',
    type: ''
})

const departments = ref<any>([])

onMounted(async () => {
    // 确保患者信息在组件挂载后获取
    try {
        const patientData = patientStore.GetPatientStore()
        patient.value = patientData || {} //// 处理null情况
        // 设置患者ID
        if (patient.value?.id) {
            form.value.patientId = patient.value.id
        }
        // 获取科室数据
        const departmentsData = await GetDepartments()
        departments.value = departmentsData.data
    }
    catch (error) {
        console.error('初始化错误:', error)
    }
})

const submitRegistration = async () => {
    const request = {
        id: 0,
        createTime: new Date(),
        status: "1", // 未处理
        patientId: form.value.patientId,
        departmentId: form.value.departmentId,
        orderId: ""
    }
    if (request.departmentId && request.patientId) {
        request.orderId = (await submitOrder()).toString()
        const response = await PostRegistration(request)
        if (response.data === true)
            alert("挂号成功")
    } else {
        alert('请填写完整的挂号信息!')
    }
}
const submitOrder = async () => {
    const request = {
        id: 0,
        outTradeNo: generateUniqueId().toString(),
        createTime: new Date(),
        subject: "预约",
        totalAmount: "10",
        body: "这是预约账单",
        orderStatus: "0" //默认为未付款
    }
    const response = await PostOrder(request)
    if (response.data.code === 200) {
        alert("订单生成成功")
    }
    return response.data
}

const paymentRequest = {
    orderNumber: "",
    subject: 'Registration',
    totalAmount: "100.00",
    body: 'Test order description',
    returnUrl: '',  // 同步回调地址
    notifyUrl: 'http://127.0.0.1:4040'   // 异步回调地址
}

const payPageHtml = ref<any>()
const dialogVisible = ref(false)
const handlePostPayment = async () => {

    dialogVisible.value = true;
    try {
        const data = await PostPayment(paymentRequest) as unknown as { payPageHtml: string } // 直接获得响应的 data
        // 检查是否有返回支付表单
        if (data?.payPageHtml) {
            payPageHtml.value = data.payPageHtml // 赋值给payPageHtml
            console.log(payPageHtml.value)
        } else {
            console.error('支付页面 HTML 未返回')
        }
    } catch (error) {
        console.error('支付请求失败:', error)
    }
}

const columns = ref<any>([])
watch(
    () => form.value.type,
    () => {
        columns.value = departments.value.filter(d => d.type === form.value.type)
    }
)
</script>

<style scoped>
.e-form {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    top: 5px;
    flex-direction: row;
    flex: auto;
    justify-content: space-between;
}

.e-form .el-form-item {
    width: 300px;
}

.el-input {
    width: 300px;
}

.el-aside {
    width: var(--el-aside-width, 256px) !important;
    background-color: var(--el-menu-bg-color);
    transition: width 0.3s;
}
</style>